package com.luck.cloud.snowflake;

import com.luck.cloud.configuration.SnowflakeAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 定时续期任务
 * 每1分钟做一次续期,申明这个key已经被占用
 * 防止redis的key丢失后被其他服务占用,导致的id冲突
 */

@Slf4j
@Component
public class RenewalTask {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 从第一分钟开始,每隔一分钟做一次续期,续期10分钟,占用这个key
     */
    @Scheduled(initialDelay = 1, fixedRate = 1, timeUnit = TimeUnit.MINUTES)
    public void execute() {
        long datacenterId = SnowflakeAutoConfiguration.DATACENTER_ID;
        long workerId = SnowflakeAutoConfiguration.WORKER_ID;
        if (datacenterId != 0 && workerId != 0) {
            String key = SnowflakeAutoConfiguration.SNOWFLAKE_MACHINE_ID_PREFIX + datacenterId + ":" + workerId;
            log.info("    redis的key:{}续期10分钟", key);
            stringRedisTemplate.opsForValue().set(key, key, 10, TimeUnit.MINUTES);
        }
    }


}